package com.hk.service.impl;

import com.hk.dao.ImageDao;
import com.hk.model.Document;
import com.hk.model.Image;
import com.hk.service.IImageService;
import com.hk.utils.Io;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: KangWang
 * Date: 2021/5/18 19:52
 * State：公共照片业务逻辑层
 */
public class ImageServiceImpl implements IImageService {

    @Override
    public List<Image> findAllImage(String path) {
        ImageDao imageDao = new ImageDao();
        List<Image> images = imageDao.findAllImage();
        //      1、存储路径  2、文件夹 3、文件
        Document document = new Document(path,"Images", "Images.txt");
//        写入数据
        writeData(images,document);
        images = (List<Image>) readData(document);
        if (images == null && images.isEmpty()) {
            System.out.println("暂无公共照片");
            return null;
        }
        return images;
    }

    /**
     * 读取数据
     * @param document
     * @return
     */
    @Override
    public List<?> readData(Document document) {
        //    根据该对象内多少属性进行转化划分
        final int count = 8;
        List<Image> images = new ArrayList<>();
        List<String> list = Io.readData(document);
//      将读取到的数据进行类型转换
        for (int i = 0; i < list.size(); i=i+count) {
            Image image = new Image(
                    Integer.parseInt(list.get(i)),
                    list.get(i+1),
                    list.get(i+2),
                    Integer.parseInt(list.get(i+3)),
                    Integer.parseInt(list.get(i+4)),
                    Integer.parseInt(list.get(i+5)),
                    Integer.parseInt(list.get(i+6)),
                    Integer.parseInt(list.get(i+7))
            );
            images.add(image);
        }
//        System.out.println("读取的转换数据Images："+images);
        return images;
    }

    /**
     * 写入数据
     * @param list
     * @param document
     */
    @Override
    public void writeData(List<?> list, Document document) {
        List<Image> images = (List<Image>) list;
        List<String> list1 = new ArrayList<>();
        for (Image image : images) {
            list1.add(String.valueOf(image.getImgId()));
            list1.add(image.getImgUrl());
            list1.add(image.getImgTitle());
            list1.add(String.valueOf(image.getCompanyId()));
            list1.add(String.valueOf(image.getnPublicId()));
            list1.add(String.valueOf(image.getDisplayId()));
            list1.add(String.valueOf(image.getmPublicId()));
            list1.add(String.valueOf(image.getUsId()));
        }
        Io.writeData(list1,document);
    }
}
